<?php
/*
*
**/
class DiseaseController{
	protected $ci;
	public static $view;
	public static $db;
	public static $wp_user;

	function __construct($ci){		
		$this->ci=$ci;
		self::$view=$ci['view'];
		self::$db=$ci['db'];
		$session=new UserSession();
		self::$wp_user=$session->get();
	}
	public function __invoke($req, $response, $args) {
		$queryParams=$req->getQueryParams();
		$p=1;
		if(!empty($queryParams['p'])){
			$p=intval($queryParams['p']);
			if(!$p)$p=1;
		}
		$per=10;
		$fromIndex=($p-1)*$per;
	    $diseases=self::$db->select('disease','*',[ "ORDER" => "id DESC","LIMIT" =>[$fromIndex,$per]]);
	    $pagination['counts']=self::$db->count('disease','*');
	    $pagination['pages']=ceil($pagination['counts']/$per);
	    $pagination['current']=$p;
	    $pagination['per']=$per;
		return self::$view->render('disease/list.twig', array('title'=>'病种列表','diseases'=>$diseases,'pagination'=>$pagination,'wp_user'=>self::$wp_user));
	}


	function add($request, $response, $args){
		$msg='';
		if($request->isPost()){
			$params=$request->getParsedBody();
			if(!empty($params['name'])){
				$handle=new FileUpload();
				if($handle -> upload("picture")) {
				    $params['picture']=$handle->getFullFileName(); 	
				    $msg='图片上传成功,';		    
				} else {
				    $msg=$handle->getErrorMsg();
				}
				if(self::$db->insert('disease',$params)){
				    	$msg.='添加病种成功';
				}else{
						$msg.='添加病种失败'.self::$db->last_query();
				}
			}else{
				$msg='病种不能为空';
			}
		}

		return self::$view->render('disease/add.twig',['msg'=>$msg,'wp_user'=>self::$wp_user]);
	}

	function edit($request, $response, $id){		
		$msg='';
		if($request->isPost()){
			$params=$request->getParsedBody();
			if(!empty($params['id'])&&!empty($params['name'])){
				$handle=new FileUpload();
				if($handle -> upload("picture")) {
				    $params['picture']=$handle->getFullFileName(); 	
				    $msg='图片上传成功,';		    
				} else {
				    $msg=$handle->getErrorMsg();
				}
				if(self::$db->update('disease',$params,['id'=>$id])){
				    	$msg.='更新病种成功';
				}else{
						$msg.='更新病种失败'.self::$db->last_query();
				}
			}else{
				$msg='病种ID不能为空';
			}
		}
		$disease=self::$db->get('disease','*',['id'=>$id]);
		return self::$view->render('disease/edit.twig',['msg'=>$msg,'disease'=>$disease,'wp_user'=>self::$wp_user]);
	}


}